<template>
    <el-container style="max-height: 30%">
        <el-header height="40px" style="position: relative;background-color:#409eff;color:white">
            <h4 style="position: absolute;width:98%;text-align:center;">
                {{current_dorm==null?'':current_dorm.code+'抄表'}}</h4>
            <router-link :to="'/dorm_list/'+$route.params.building_id" class="fa fa-close"
                         style="position: absolute;color:red;right:5px;top:5px"></router-link>
        </el-header>
        <div style="margin: 10px 5px">
            <el-form :inline="true" :model="formInline" :rules="rules" ref="form">
                <el-form-item label="隶属周期" required>
                    <el-select v-model="formInline.period_id">
                        <el-option v-for="period in history_period" :label="period.name" :value="period.id"
                                   :key="period.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="上次抄表日期" prop="prev_record_date">
                    <el-date-picker v-model="formInline.prev_record_date" type="date" placeholder="选择日期"
                                    value-format="yyyy-MM-dd" :picker-options="pickerOptions"
                                    :disabled="formInline.prev_record_id!=null">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="上次电表读数" prop="electric_prev_reading">
                    <el-input-number v-model="formInline.electric_prev_reading" :precision="2" :step="0.1"
                                     :disabled="formInline.prev_record_id!=null" :min="0"></el-input-number>
                </el-form-item>
                <el-form-item label="上次水表读数" prop="water_prev_reading">
                    <el-input-number v-model="formInline.water_prev_reading" :precision="2" :step="0.1"
                                     :disabled="formInline.prev_record_id!=null" :min="0"></el-input-number>
                </el-form-item>
                <el-form-item label="抄表日期" prop="record_date">
                    <el-date-picker v-model="formInline.record_date" type="date" placeholder="选择日期"
                                    value-format="yyyy-MM-dd" :picker-options="pickerOptions">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="电表读数" prop="electric_reading">
                    <el-input-number v-model="formInline.electric_reading" :precision="2" :step="0.1"
                                     :min="0"></el-input-number>
                </el-form-item>
                <el-form-item label="水表读数" prop="water_reading">
                    <el-input-number v-model="formInline.water_reading" :precision="2" :step="0.1"
                                     :min="0"></el-input-number>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="formInline.remark" placeholder="备注信息"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-checkbox v-model="formInline.change_water_meter" :disabled="meter_change_disable">换水表
                    </el-checkbox>
                </el-form-item>
                <el-form-item>
                    <el-checkbox v-model="formInline.change_electric_meter" :disabled="meter_change_disable">换电表
                    </el-checkbox>
                </el-form-item>
                <el-form-item>
                    <el-button type="success" @click="toPrevRec" :disabled="formInline.prev_record_id==null">上一条
                    </el-button>
                    <el-button type="warning" @click="newRec">新记录</el-button>
                    <el-button type="primary" @click="onSubmit">{{formInline.id==null?'保存':'更新'}}</el-button>
                    <el-button type="danger" @click="deleteRec" :disabled="formInline.id==null">删除</el-button>
                </el-form-item>
            </el-form>
        </div>
    </el-container>
</template>
<script>
    export default {
        props: ['dorm_id'],
        created(){
            this.initData(this.dorm_id);
        },
        watch: {
            'dorm_id': function (to, from) {
                this.initData(to);
            },
            'formInline.change_water_meter': function (to, from) {
                if (to) {
                    this.formInline.electric_reading = this.formInline.electric_prev_reading;
                    this.formInline.record_date = this.formInline.prev_record_date;
                    this.formInline.period_id = this.history_period[0].id;
                    this.formInline.remark += ' 换水表';
                }
            },
            'formInline.change_electric_meter': function (to, from) {
                if (to) {
                    this.formInline.water_reading = this.formInline.water_prev_reading;
                    this.formInline.record_date = this.formInline.prev_record_date;
                    this.formInline.period_id = this.history_period[0].id;
                    this.formInline.remark += ' 换电表';
                }
            },
        },
        data() {
            var checkWaterRec = (rule, value, callback) => {
                if (this.formInline.change_water_meter == false) {
                    if (value < this.formInline.water_prev_reading) {
                        return callback(new Error('读数不能小于等于上一次抄表'));
                    } else {
                        return callback();
                    }
                } else {
                    return callback();
                }
            };
            var checkEletricRec = (rule, value, callback) => {
                if (this.formInline.change_electric_meter == false) {
                    if (value < this.formInline.electric_prev_reading) {
                        return callback(new Error('读数不能小于等于上一次抄表'));
                    } else {
                        return callback();
                    }
                } else {
                    return callback();
                }
            };
            var checkPeriod = (rule, value, callback) => {
                var selected_period = this.history_period.find(function (p) {
                    return p.id == this.formInline.period_id;
                }, this);
                const start_date = new Date(selected_period.start_date);
                const end_date = new Date(selected_period.end_date);
                const prev_record_date = new Date(this.formInline.prev_record_date);
                const record_date = new Date(this.formInline.record_date);
                if (prev_record_date >= start_date && prev_record_date < end_date) {
                    return callback();
                } else if (prev_record_date < start_date && record_date > start_date) {
                    return callback();
                } else {
                    return callback(new Error('与隶属周期起始时间不匹配'));
                }

            };
            var checkDate = (rule, value, callback) => {
                if (new Date(value) > new Date()) {
                    return callback(new Error('抄表日期不能大于今天'));
                } else if (new Date(this.formInline.record_date) < new Date(this.formInline.prev_record_date)) {
                    return callback(new Error('抄表日期必须大于等于上次抄表日期'));
                } else {
                    return callback();
                }
            };
            return {
                formInline: {
                    id: null,
                    period_id: '',
                    dorm_id: '',
                    prev_record_id: null,
                    electric_prev_reading: '',
                    electric_reading: '',
                    water_prev_reading: '',
                    water_reading: '',
                    prev_record_date: '',
                    record_date: '',
                    change_water_meter: false,
                    change_electric_meter: false,
                    remark: ''
                },
                rules: {
                    period_id: [
                        {required: true, message: '请选择隶属周期', trigger: 'change'},
                    ],
                    electric_prev_reading: [
                        {required: true, message: '请填写上次电表读数', trigger: 'change'}
                    ],
                    electric_reading: [
                        {required: true, message: '请填写电表读数', trigger: 'change'},
                        {validator: checkEletricRec, trigger: 'blur'}
                    ],
                    water_prev_reading: [
                        {required: true, message: '请填写上次水表读数', trigger: 'change'}
                    ],
                    water_reading: [
                        {required: true, message: '请填写水表读数', trigger: 'change'},
                        {validator: checkWaterRec, trigger: 'blur'}
                    ],
                    prev_record_date: [
                        {required: true, message: '请选择上次抄表日期', trigger: 'change'},
                        {validator: checkDate, trigger: 'blur'},
                        {validator: checkPeriod, trigger: 'blur'}
                    ],
                    record_date: [
                        {required: true, message: '请选择抄表日期', trigger: 'change'},
                        {validator: checkDate, trigger: 'blur'},
                        {validator: checkPeriod, trigger: 'blur'}
                    ]
                },
                current_record_idx: 0,
                meter_change_disable: true,
                current_dorm: null,
                history_period: [],
                pickerOptions: {
                    disabledDate(time) {
                        return time.getTime() > Date.now();
                    },
                    shortcuts: [{
                        text: '今天',
                        onClick(picker) {
                            picker.$emit('pick', new Date());
                        }
                    }, {
                        text: '1号',
                        onClick(picker) {
                            const date = new Date();
                            date.setDate(1);
                            picker.$emit('pick', date);
                        }
                    }, {
                        text: '上月1号',
                        onClick(picker) {
                            const date = new Date();
                            date.setMonth(date.getMonth() - 1);
                            date.setDate(1);
                            picker.$emit('pick', date);
                        }
                    }]
                },
            }
        },
        methods: {
            initData(dorm_id){
                this.dorm_id=dorm_id;
                this.current_record_idx=0;
                if (this.$refs['form']) {
                    this.$refs['form'].resetFields();
                }
                this.formInline.id = null;
                this.formInline.prev_record_id = null;
                this.formInline.dorm_id = dorm_id;
                axios.get('api/v1/dorm/' + dorm_id).then(result => {
                    this.current_dorm = result.data;
                });
                axios.get('api/v1/period?log_date=' + new Date().toISOString().slice(0, 10)).then(result => {
                    this.history_period = result.data;
                    if (new Date().getDate() < 10) {
                        if (this.history_period.length > 1) {
                            this.formInline.period_id = this.history_period[1].id;
                        }
                    } else {
                        if (this.history_period.length > 0) {
                            this.formInline.period_id = this.history_period[0].id;
                        }
                    }
                }).catch(error => {
                    console.log(error);
                });

                axios.get('api/v1/dormMeterRecord?dorm_id=' + this.dorm_id).then(result => {
                    var rec = result.data;
                    var today = new Date().toISOString().slice(0, 10);
                    if (rec) {
                        this.formInline.prev_record_id = rec.id;
                        this.formInline.prev_record_date = rec.record_date;
                        this.formInline.water_prev_reading = rec.water_reading;
                        this.formInline.electric_prev_reading = rec.electric_reading;
                        if (this.formInline.prev_record_date == today) {
                            this.meter_change_disable = false;
                        }
                        ;
                    } else {
                        this.formInline.prev_record_date = '';
                        this.formInline.water_prev_reading = '';
                        this.formInline.electric_prev_reading = '';
                        this.meter_change_disable = true;
                    }
                });
            },
            onSubmit() {
                console.log(this.formInline.id == null);
                if (this.formInline.id == null) {
                    this.$refs['form'].validate(result => {
                        if (result) {
                            axios.post('api/v1/dormMeterRecord', this.formInline).then(result => {
                                this.$notify({message: '录入成功', type: 'success'});
                                this.formInline.id = result.data.id;
                                this.initData(this.dorm_id);
                            }).catch(error => {
                                console.log(error);
                                this.$notify.error({message: '录入失败'});
                            });
                        }
                    });
                } else {
                    this.$refs['form'].validate(result => {
                        if (result) {
                            axios.put('api/v1/dormMeterRecord/' + this.formInline.id, this.formInline).then(result => {
                                this.$notify({message: '更新成功', type: 'success'});
                            }).catch(error => {
                                console.log(error);
                                this.$notify.error({message: '更新失败'});
                            });
                        }
                    });
                }

            },
            toPrevRec(){
                axios.get('api/v1/dormMeterRecord/' + this.formInline.prev_record_id).then(result => {
                    this.formInline = _.cloneDeep(result.data);
                });
                this.current_record_idx++;
            },
            deleteRec(){
                if(this.current_record_idx==1){
                    this.$confirm('确定要删除最近一条记录?', '删除提示').then(
                        () => {
                            axios.delete('api/v1/dormMeterRecord/' + this.formInline.id).then(
                                result => {
                                    this.$notify({message: '删除成功', type: 'success'});
                                    this.initData(this.dorm_id);
                                }).catch(error => {
                                    console.log('删除失败' + error);
                                }
                            );
                        }).catch(action => {
                            console.log(action);
                        }
                    );
                }else{
                    this.$notify.warning('只能删除最新的一条记录');
                }
            },
            newRec(){
                this.initData(this.dorm_id);
            }
        }
    }
</script>
